import os
import json
from werkzeug.security import generate_pass_hash

# 数据路径
data_dir = os.path.join(os.path.dirname(__file__), 'data')
cards_file = os.path.join(data_dir, 'cards.json')

# 加载函数
def load_json(path):
    with open(path, 'r', encoding='utf-8') as f:
        return json.load(f)

# 保存函数
def save_json(path, data):
    with open(path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

# 执行加密
def encrypt_card_pass():
    cards = load_json(cards_file)
    changed = False

    for card in cards:
        pwd = card.get('pass', '')
        if pwd and not pwd.startswith('pbkdf2:sha256'):
            card['pass'] = generate_pass_hash(pwd)
            changed = True
            print(f"🔐 卡号 {card['cardID']} 密码已加密")

    if changed:
        save_json(cards_file, cards)
        print("✅ 所有明文密码已加密完成")
    else:
        print("✅ 所有卡密码本身已加密，无需处理")

if __name__ == '__main__':
    encrypt_card_passwords()
